package com.practice;

import java.util.ArrayList;

public class DoPasty {
    ArrayList<String> list =new ArrayList<>();
    public synchronized void cook(){
        if (list.isEmpty()) {
            String name = System.currentTimeMillis() + "";
            list.add(name);
            System.out.println(Thread.currentThread().getName() + "做了一个包子：" + name);
            try {
                Thread.sleep(300);
                this.notifyAll();
                this.wait();
               } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                Thread.sleep(300);
                this.notifyAll();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }
    private synchronized void eat(){
        if (!list.isEmpty()){
            System.out.println(Thread.currentThread().getName() + "吃了一个包子" + list.remove(0));
            try {
                Thread.sleep(200);
                this.notify();
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else {
            try {
                Thread.sleep(200);
                this.notify(); // 通知厨师做包子
                this.wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static void main(String[] args) {
        DoPasty pasty = new DoPasty();
        Thread thread1 = new Thread(() ->{
            while (true) {
                pasty.cook();
            }
        },"小福贵");
        Thread thread2 = new Thread(() ->{
            while (true) {
                pasty.cook();
            }
        },"小当家");
        Thread thread3 = new Thread(() ->{
            while (true) {
                pasty.cook();
            }
        },"灰太狼");
        Thread thread4 = new Thread(() ->{
            while (true) {
                pasty.eat();
            }
        },"懒洋洋");
        Thread thread5 = new Thread(() ->{
            while (true) {
                pasty.eat();
            }
        },"猪八戒");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}
